import { BaseSession } from './base'
import { toAny, Int32Value, fromAny, StringValue, BoolValue } from '../proto'
import { announceStatusMessage } from '../utils'
import { Message } from 'protobufjs'
export class ActivitySession extends BaseSession {
    private isStopped = true
    private isPaused = true
    private clientWidth = 0
    private clientHeight = 0
    private onVisibleChange: () => void;
    constructor(render: HTMLElement) {
        super('Activity', render)
        render.innerHTML = ''
        this.clientWidth = render.clientWidth
        this.clientHeight = render.clientHeight
    }
    onConnect() {
        super.onConnect();
        this.onCreate()
    }
    onCreate(sessionId: number = 0, futureId: number = 0, ...argv) {
        super.onCreate(sessionId, futureId, ...argv);
        this.onVisibleChange = () => {
            if(document.visibilityState == 'visible') this.resume()
            else if (document.visibilityState == 'hidden') this.pause()
        }
        document.addEventListener("visibilitychange", this.onVisibleChange);
        window.onpopstate = () => this.backPressed()
        this.start()
    }
    onDestroy() {
        document.removeEventListener("visibilitychange", this.onVisibleChange)
        super.onDestroy();
    }
    onReceive(name: String, sessionId: number, futureId: number, ...argv) {
        switch (name) {
            case 'getScreenSize':
                return this.getScreenSize(sessionId, futureId)
            case 'setTitle':
                return this.setTitle(...argv)
            case 'getTitle':
                return this.getTitle(sessionId, futureId)
            case 'accessibilityNotice':
                return this.accessibilityNotice(...argv)
            case 'setTouchExploration':
                return this.setTouchExploration(...argv)
            case 'setClipboardText':
                return this.setClipboardText(...argv)
            case 'getClipboardText':
                return this.getClipboardText(sessionId, futureId)
        }
        super.onReceive(name, sessionId, futureId, ...argv);
    }
    start() {
        if (this.isStopped)
            this.onStart()
        this.isStopped = false
    }
    stop () {
        if (!this.isStopped)
            this.onStop()
        this.isStopped = true
    }
    destroy() {
        this.stop()
        super.destroy();
    }
    private backPressed() {
        if (!document.URL.endsWith('#/launch'))
            this.onBackPressed()
    }
    private pause() {
        if (!this.isPaused)
            this.onPause()
        this.isPaused = true
    }
    resume() {
        if (this.isPaused)
            this.onResume()
        this.isPaused = false
    }
    private onStart () {
        this.sendAction('onStart')
        this.resume()
    }
    private onStop () {
        this.pause()
        this.sendAction('onStop')
    }
    private onResume () {
        this.sendAction('onResume')
    }
    private onPause () {
        this.sendAction('onPause')
    }
    private onBackPressed() {
        this.sendActionUntilCallbackResult('onBackPressed').then((res: Message) => {
            const ret = fromAny(res, BoolValue)
            if (!ret)
                history.go(1)
        })
    }
    private getScreenSize(sessionId: number, futureId: number) {
        const width = toAny(this.clientWidth, Int32Value)
        const height = toAny(this.clientHeight, Int32Value)
        this.sendAction('onGetScreenSize', sessionId, futureId, width, height)
    }
    private setTitle(...argv) {
        document.title = fromAny(argv[0], StringValue)
    }
    private getTitle(sessionId: number, futureId: number) {
        this.sendAction("onGetTitle", sessionId, futureId, toAny(document.title, StringValue))
    }
    private accessibilityNotice(...argv) {
        announceStatusMessage(fromAny(argv[0], StringValue))
    }
    private setTouchExploration(...argv) {
        const enabled = fromAny(argv[0], BoolValue)
        const platformMode = (navigator.userAgent.toLowerCase().indexOf('windows') > -1) ? '浏览模式' : '触摸浏览'
        announceStatusMessage('请' + (enabled ? '开启' : '关闭') + platformMode + '继续操作！')
    }
    private setClipboardText(...argv) {
        navigator.clipboard.writeText(fromAny(argv[0], StringValue)).catch((error: Error) => {
            this.onError(error)
        })
    }
    private getClipboardText(sessionId: number, futureId: number) {
        navigator.clipboard?.readText().then((clipboardText) => {
            this.sendAction("onGetClipboardText", sessionId, futureId, toAny(clipboardText, StringValue))
        }).catch((error: Error) => {
            this.onError(error, sessionId, futureId)
        });
    }
}